package com.rpframework.core.config.zookeeper;

import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.data.Stat;

/**
 * zookeeper客户端连接
 * 
 * @author 刘兴
 */
public class ZooKeeperConfig implements Config {
	/**
	 * 客户端
	 */
	private ZooKeeperFactory zooKeeperFactory;

	public ZooKeeperFactory getZooKeeperFactory() {
		return zooKeeperFactory;
	}

	public void setZooKeeperFactory(ZooKeeperFactory zooKeeperFactory) {
		this.zooKeeperFactory = zooKeeperFactory;
	}

	@Override
	public byte[] getConfig(String path) throws Exception {
		CuratorFramework client = zooKeeperFactory.get();
		if (!exists(client, path)) {
			throw new RuntimeException("地址[ " + path + " ]不存在");
		}
		return client.getData().forPath(path);
	}

	/**
	 * 检测地址是否存在
	 * 
	 * @param client
	 *            客户端
	 * @param path
	 *            地址
	 * @return 存在-true/不存在-false
	 * @throws Exception
	 *             客户端异常
	 */
	private boolean exists(CuratorFramework client, String path) throws Exception {
		Stat stat = client.checkExists().forPath(path);
		return !(stat == null);
	}

}